package com.shu.project.controller;

import com.shu.framework.enums.CodeMsg;
import com.shu.framework.utils.StringUtils;
import com.shu.project.model.Order;
import com.shu.project.model.User;
import com.shu.project.service.IGoodsService;
import com.shu.project.service.IOrderService;
import com.shu.project.service.ISeckillService;
import com.shu.project.vo.GoodsVo;
import com.shu.project.vo.SeckillOrderVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/seckill")
public class SeckillController {
    @Autowired
    IGoodsService goodsService;
    @Autowired
    IOrderService orderService;
    @Autowired
    ISeckillService seckillService;
    @RequestMapping("/do_seckill")
    public String doSeckill(Model model, User user,@RequestParam("goodsId") Long goodsId){
        if (StringUtils.isNull(user)){return "login";}
        model.addAttribute("user",user);
        //判断库存
        GoodsVo goodsVo = goodsService.queryGoodsVoById(goodsId);
        if (goodsVo.getStockCount()<=0){
            model.addAttribute("errorMsg",CodeMsg.SECKILL_OVER.msg);
            return "seckill_fail";
        }
        //判断是否已经存在订单
        Map<String,Long> queryOrderMap = new HashMap<String,Long>();
        queryOrderMap.put("userId",user.getId());
        queryOrderMap.put("goodsId",goodsId);
        List<SeckillOrderVo> orderVos = orderService.queryOrderByUserIdGoodsId(queryOrderMap);
        if (!StringUtils.isEmpty(orderVos)){
            model.addAttribute("errorMsg",CodeMsg.SECKILL_REPEATE.msg);
            return "seckill_fail";
        }
        //秒杀开始
        Order order = seckillService.seckill(user, goodsVo);
        if (!StringUtils.isNull(order)){
            model.addAttribute("order",order);
            model.addAttribute("goods",goodsVo);
        }
        return "order_detail";
    }
}
